package cn.itsource.ymcc.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.itsource.ymcc.constant.CacheConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.errorcode.ErrorCode;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICommonService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.CodeGenerateUtils;
import cn.itsource.ymcc.util.StrUtils;
import cn.itsource.ymcc.util.VerifyCodeUtils;
import cn.itsource.ymcc.vo.PhoneCodeVo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class CommonServiceImpl implements ICommonService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public JsonResult getImageCode(String imgCodeKey) {
        AssertUtil.isNotNull(imgCodeKey,"请求参数异常");
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(300, 100, RConst.Num.INT_4, RConst.Num.INT_4);
        String code = captcha.getCode();
        //存入redis
        redisTemplate.opsForValue().set(imgCodeKey,code, Duration.ofMinutes(RConst.Num.INT_3));

        String imageBase64 = captcha.getImageBase64();

        return JsonResult.success().setData(imageBase64);
    }

    @Override
    public JsonResult sendSmsCode(PhoneCodeVo phoneCodeVo) {
        //查询图片验证码是否过期
        Boolean key = redisTemplate.hasKey(phoneCodeVo.getUuid());
        AssertUtil.isTrue(key,"验证码已过期");
        String imgCode = redisTemplate.opsForValue().get(phoneCodeVo.getUuid()).toString();
        AssertUtil.isEquals(phoneCodeVo.getImageCode(), imgCode, ErrorCode.IMG_CODE_INPUT_ERROR.getMessage());

        //生成手机号验证码
        String phoneCode = StrUtils.getRandomString(RConst.Num.INT_6);

        //判断redis是否存在
        Boolean aBoolean = redisTemplate.hasKey(CacheConstants.PHONE_CODE_KEY + phoneCodeVo.getMobile());
        if (aBoolean){
            Long expire = redisTemplate.getExpire(CacheConstants.PHONE_CODE_KEY);
            if (expire>RConst.Num.LONG_240){
                throw new GlobalException(ErrorCode.ILLEGAL_REQUEST);
            }
            phoneCode = redisTemplate.opsForValue().get(CacheConstants.PHONE_CODE_KEY + phoneCodeVo.getMobile()).toString();
            //调用发短信的接口
        }
        redisTemplate.opsForValue().set(CacheConstants.PHONE_CODE_KEY+phoneCodeVo.getMobile(),phoneCode,Duration.ofMinutes(RConst.Num.INT_5));
        System.out.println(phoneCode);

        return JsonResult.success();
    }
}
